package com.example.api.controller;

import com.example.api.dto.TenantCreateDTO;
import com.example.api.dto.TenantUpdateDTO;
import com.example.service.entity.SystemTenant;
import com.example.service.service.SystemTenantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 租户控制器
 * 提供租户相关的REST API接口
 * 
 * @author example
 * @since 1.0.0
 */
@RestController
@RequestMapping("/api/tenants")
@Tag(name = "租户管理", description = "租户相关的API接口，包括创建、查询、更新和删除租户等操作")
public class SystemTenantController {

    private final SystemTenantService tenantService;

    /**
     * 构造函数注入SystemTenantService
     * 
     * @param tenantService 租户服务
     */
    @Autowired
    public SystemTenantController(SystemTenantService tenantService) {
        this.tenantService = tenantService;
    }

    /**
     * 创建新租户
     * 
     * @param tenantDTO 租户创建DTO
     * @return 创建成功的租户对象
     */
    @Operation(summary = "创建新租户", description = "创建一个新的租户，租户名称必须唯一")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "201", description = "租户创建成功", 
                    content = @Content(schema = @Schema(implementation = SystemTenant.class))),
        @ApiResponse(responseCode = "400", description = "请求参数错误，如租户名称已存在")
    })
    @PostMapping
    public ResponseEntity<SystemTenant> createTenant(@Valid @RequestBody TenantCreateDTO tenantDTO) {
        try {
            // 将DTO转换为实体
            SystemTenant tenant = new SystemTenant();
            tenant.setName(tenantDTO.getName());
            tenant.setNickname(tenantDTO.getNickname());
            tenant.setEmail(tenantDTO.getEmail());
            tenant.setPhone(tenantDTO.getPhone());
            tenant.setAddress(tenantDTO.getAddress());
            tenant.setPermissionStart(tenantDTO.getPermissionStart());
            tenant.setPermissionEnd(tenantDTO.getPermissionEnd());
            tenant.setPermissionUserCount(tenantDTO.getPermissionUserCount());
            
            SystemTenant createdTenant = tenantService.createTenant(tenant);
            return new ResponseEntity<>(createdTenant, HttpStatus.CREATED);
        } catch (IllegalArgumentException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 更新租户信息
     * 
     * @param tenantDTO 租户更新DTO
     * @return 更新后的租户对象
     */
    @Operation(summary = "更新租户信息", description = "更新指定ID的租户信息，租户名称必须唯一")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "租户信息更新成功", 
                    content = @Content(schema = @Schema(implementation = SystemTenant.class))),
        @ApiResponse(responseCode = "400", description = "请求参数错误，如租户不存在或租户名称已被其他租户使用"),
        @ApiResponse(responseCode = "404", description = "租户不存在")
    })
    @PutMapping
    public ResponseEntity<SystemTenant> updateTenant(@Valid @RequestBody TenantUpdateDTO tenantDTO) {
        try {
            // 将DTO转换为实体
            SystemTenant tenant = new SystemTenant();
            tenant.setId(tenantDTO.getId());
            tenant.setName(tenantDTO.getName());
            tenant.setNickname(tenantDTO.getNickname());
            tenant.setEmail(tenantDTO.getEmail());
            tenant.setPhone(tenantDTO.getPhone());
            tenant.setAddress(tenantDTO.getAddress());
            tenant.setPermissionStart(tenantDTO.getPermissionStart());
            tenant.setPermissionEnd(tenantDTO.getPermissionEnd());
            tenant.setPermissionUserCount(tenantDTO.getPermissionUserCount());
            tenant.setStatus(tenantDTO.getStatus());
            
            SystemTenant updatedTenant = tenantService.updateTenant(tenant);
            return new ResponseEntity<>(updatedTenant, HttpStatus.OK);
        } catch (IllegalArgumentException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 获取所有租户
     * 
     * @return 租户列表
     */
    @Operation(summary = "获取所有租户", description = "获取系统中所有租户的列表")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取租户列表", 
                    content = @Content(schema = @Schema(implementation = List.class)))
    })
    @GetMapping
    public ResponseEntity<List<SystemTenant>> getAllTenants() {
        List<SystemTenant> tenants = tenantService.findAllTenants();
        return new ResponseEntity<>(tenants, HttpStatus.OK);
    }

    /**
     * 分页查询租户
     * 
     * @param pageable 分页参数
     * @return 租户分页结果
     */
    @Operation(summary = "分页查询租户", description = "分页获取租户列表")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取租户分页结果", 
                    content = @Content(schema = @Schema(implementation = Page.class)))
    })
    @GetMapping("/page")
    public ResponseEntity<Page<SystemTenant>> getTenantsByPage(Pageable pageable) {
        Page<SystemTenant> tenants = tenantService.findTenantsByPage(pageable);
        return new ResponseEntity<>(tenants, HttpStatus.OK);
    }

    /**
     * 根据ID获取租户
     * 
     * @param id 租户ID
     * @return 租户对象
     */
    @Operation(summary = "根据ID获取租户", description = "根据租户ID获取租户详细信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取租户信息", 
                    content = @Content(schema = @Schema(implementation = SystemTenant.class))),
        @ApiResponse(responseCode = "404", description = "租户不存在")
    })
    @GetMapping("/{id}")
    public ResponseEntity<SystemTenant> getTenantById(
            @Parameter(description = "租户ID", required = true, example = "1") 
            @PathVariable Long id) {
        Optional<SystemTenant> tenantOptional = tenantService.findTenantById(id);
        return tenantOptional
                .map(tenant -> new ResponseEntity<>(tenant, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 根据名称获取租户
     * 
     * @param name 租户名称
     * @return 租户对象
     */
    @Operation(summary = "根据名称获取租户", description = "根据租户名称获取租户详细信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取租户信息", 
                    content = @Content(schema = @Schema(implementation = SystemTenant.class))),
        @ApiResponse(responseCode = "404", description = "租户不存在")
    })
    @GetMapping("/name/{name}")
    public ResponseEntity<SystemTenant> getTenantByName(
            @Parameter(description = "租户名称", required = true, example = "示例租户") 
            @PathVariable String name) {
        Optional<SystemTenant> tenantOptional = tenantService.findTenantByName(name);
        return tenantOptional
                .map(tenant -> new ResponseEntity<>(tenant, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 根据邮箱获取租户
     * 
     * @param email 租户邮箱
     * @return 租户对象
     */
    @Operation(summary = "根据邮箱获取租户", description = "根据租户邮箱获取租户详细信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取租户信息", 
                    content = @Content(schema = @Schema(implementation = SystemTenant.class))),
        @ApiResponse(responseCode = "404", description = "租户不存在")
    })
    @GetMapping("/email/{email}")
    public ResponseEntity<SystemTenant> getTenantByEmail(
            @Parameter(description = "租户邮箱", required = true, example = "tenant@example.com") 
            @PathVariable String email) {
        Optional<SystemTenant> tenantOptional = tenantService.findTenantByEmail(email);
        return tenantOptional
                .map(tenant -> new ResponseEntity<>(tenant, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 根据电话获取租户
     * 
     * @param phone 租户电话
     * @return 租户对象
     */
    @Operation(summary = "根据电话获取租户", description = "根据租户电话获取租户详细信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取租户信息", 
                    content = @Content(schema = @Schema(implementation = SystemTenant.class))),
        @ApiResponse(responseCode = "404", description = "租户不存在")
    })
    @GetMapping("/phone/{phone}")
    public ResponseEntity<SystemTenant> getTenantByPhone(
            @Parameter(description = "租户电话", required = true, example = "13800138000") 
            @PathVariable Long phone) {
        Optional<SystemTenant> tenantOptional = tenantService.findTenantByPhone(phone);
        return tenantOptional
                .map(tenant -> new ResponseEntity<>(tenant, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 删除租户（逻辑删除）
     * 
     * @param id 租户ID
     * @return 操作结果
     */
    @Operation(summary = "删除租户", description = "逻辑删除指定ID的租户")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "204", description = "租户删除成功"),
        @ApiResponse(responseCode = "404", description = "租户不存在")
    })
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTenant(
            @Parameter(description = "租户ID", required = true, example = "1") 
            @PathVariable Long id) {
        boolean deleted = tenantService.deleteTenant(id);
        return deleted 
                ? new ResponseEntity<>(HttpStatus.NO_CONTENT)
                : new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    /**
     * 物理删除租户
     * 
     * @param id 租户ID
     * @return 操作结果
     */
    @Operation(summary = "物理删除租户", description = "物理删除指定ID的租户")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "204", description = "租户删除成功"),
        @ApiResponse(responseCode = "404", description = "租户不存在")
    })
    @DeleteMapping("/remove/{id}")
    public ResponseEntity<Void> removeTenant(
            @Parameter(description = "租户ID", required = true, example = "1") 
            @PathVariable Long id) {
        try {
            tenantService.removeTenant(id);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 检查租户名称是否已存在
     * 
     * @param name 租户名称
     * @return 检查结果
     */
    @Operation(summary = "检查租户名称是否存在", description = "检查指定的租户名称是否已被使用")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "检查完成", 
                    content = @Content(schema = @Schema(implementation = Map.class)))
    })
    @GetMapping("/check/name/{name}")
    public ResponseEntity<Map<String, Boolean>> checkTenantNameExists(
            @Parameter(description = "租户名称", required = true, example = "示例租户") 
            @PathVariable String name) {
        boolean exists = tenantService.isTenantNameExists(name);
        return new ResponseEntity<>(Map.of("exists", exists), HttpStatus.OK);
    }

    /**
     * 检查租户邮箱是否已存在
     * 
     * @param email 租户邮箱
     * @return 检查结果
     */
    @Operation(summary = "检查租户邮箱是否存在", description = "检查指定的租户邮箱是否已被使用")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "检查完成", 
                    content = @Content(schema = @Schema(implementation = Map.class)))
    })
    @GetMapping("/check/email/{email}")
    public ResponseEntity<Map<String, Boolean>> checkTenantEmailExists(
            @Parameter(description = "租户邮箱", required = true, example = "tenant@example.com") 
            @PathVariable String email) {
        boolean exists = tenantService.isTenantEmailExists(email);
        return new ResponseEntity<>(Map.of("exists", exists), HttpStatus.OK);
    }

    /**
     * 检查租户电话是否已存在
     * 
     * @param phone 租户电话
     * @return 检查结果
     */
    @Operation(summary = "检查租户电话是否存在", description = "检查指定的租户电话是否已被使用")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "检查完成", 
                    content = @Content(schema = @Schema(implementation = Map.class)))
    })
    @GetMapping("/check/phone/{phone}")
    public ResponseEntity<Map<String, Boolean>> checkTenantPhoneExists(
            @Parameter(description = "租户电话", required = true, example = "13800138000") 
            @PathVariable Long phone) {
        boolean exists = tenantService.isTenantPhoneExists(phone);
        return new ResponseEntity<>(Map.of("exists", exists), HttpStatus.OK);
    }

    /**
     * 查找授权用户数小于授权用户总数的租户
     * 
     * @return 租户列表
     */
    @Operation(summary = "查找可用用户槽的租户", description = "查找授权用户数小于授权用户总数的租户")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取租户列表", 
                    content = @Content(schema = @Schema(implementation = List.class)))
    })
    @GetMapping("/available-slots")
    public ResponseEntity<List<SystemTenant>> getTenantsWithAvailableUserSlots() {
        List<SystemTenant> tenants = tenantService.findTenantsWithAvailableUserSlots();
        return new ResponseEntity<>(tenants, HttpStatus.OK);
    }

    /**
     * 查找即将过期的租户
     * 
     * @param days 天数
     * @return 租户列表
     */
    @Operation(summary = "查找即将过期的租户", description = "查找在指定天数内即将过期的租户")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取租户列表", 
                    content = @Content(schema = @Schema(implementation = List.class)))
    })
    @GetMapping("/expiring/{days}")
    public ResponseEntity<List<SystemTenant>> getTenantsExpiringInDays(
            @Parameter(description = "天数", required = true, example = "30") 
            @PathVariable int days) {
        List<SystemTenant> tenants = tenantService.findTenantsExpiringInDays(days);
        return new ResponseEntity<>(tenants, HttpStatus.OK);
    }

    /**
     * 增加租户已用用户数
     * 
     * @param id 租户ID
     * @return 操作结果
     */
    @Operation(summary = "增加租户已用用户数", description = "增加指定ID租户的已用用户数")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功"),
        @ApiResponse(responseCode = "404", description = "租户不存在")
    })
    @PutMapping("/{id}/increment-user-count")
    public ResponseEntity<Void> incrementReadyUserCount(
            @Parameter(description = "租户ID", required = true, example = "1") 
            @PathVariable Long id) {
        boolean success = tenantService.incrementReadyUserCount(id);
        return success 
                ? new ResponseEntity<>(HttpStatus.OK)
                : new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    /**
     * 减少租户已用用户数
     * 
     * @param id 租户ID
     * @return 操作结果
     */
    @Operation(summary = "减少租户已用用户数", description = "减少指定ID租户的已用用户数")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功"),
        @ApiResponse(responseCode = "404", description = "租户不存在")
    })
    @PutMapping("/{id}/decrement-user-count")
    public ResponseEntity<Void> decrementReadyUserCount(
            @Parameter(description = "租户ID", required = true, example = "1") 
            @PathVariable Long id) {
        boolean success = tenantService.decrementReadyUserCount(id);
        return success 
                ? new ResponseEntity<>(HttpStatus.OK)
                : new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
} 